import { fetchGetData,fetchPostData,adminUrl } from '@/libs/fetch.js';
import loadChild  from '@/libs/loadChild.js';
import loadMain from '@/libs/loadMain.js';
//static
import {appRouter} from '@/router/router';
let util = {};
util.title = function (title) {
    title = title || 'iview-ui';
    window.document.title = title;
};

util.session = function(key, value){
    if (value === void(0)) {
        return JSON.parse(sessionStorage.getItem(key));
    }else {
        if (typeof(value)==="object" || Array.isArray(value)) {
            value =JSON.stringify(value);
        };
        return sessionStorage.setItem(key, value);
    }
}
//深拷贝
util.deepcopy = function (source) {
    if (!source) {
        return source;
    }
    let sourceCopy = source instanceof Array ? [] : {};
    for (let item in source) {
        sourceCopy[item] = typeof source[item] === 'object' ? util.deepcopy(source[item]) : source[item];
    }
    return sourceCopy;
};
//菜单数据组织
util.buildMenu = function (array, ckey) {
    let menuData = [];
    if(array==null){
        return menuData;
    }
    let indexKeys = Array.isArray(array) ? array.map((e) => {return e.id}) : [];
    ckey = ckey || 'parentId';
    array.map(function (item) {
        //一级菜单
        if (!item[ckey] || (item[ckey]===item.id)) {
            delete item[ckey];
            menuData.push(util.deepcopy(item)); //深拷贝
        }else if(Array.isArray(indexKeys)){
            //检测ckey有效性
            let parentIndex = indexKeys.findIndex(function(id){
                return id == item[ckey];
            });
            if(parentIndex===-1){
                menuData.push(item);
            }
        }
    });
    let findChildren = function (parentArr) {
        if (Array.isArray(parentArr) && parentArr.length) {
            parentArr.forEach(function (parentNode) {
                array.forEach(function (node) {
                    if (parentNode.id === node[ckey]) {
                        if (parentNode.children) {
                            parentNode.children.push(node);
                        } else {
                            parentNode.children = [node];
                        }
                    }
                });
                if (parentNode.children) {
                    findChildren(parentNode.children);
                }
            });
        }
    };
    findChildren(menuData);
    return menuData;
}
//遍历选中的节点 返回结果对象(无子节点)
util.mapTree=function (dataArray) {
  let res={reskey:[], resvalue:''};
  dataArray.forEach(function (item,index){
    let line=(dataArray.length-1)==index?'':'/';
    if(item.checked){
      res.resvalue+=item.title+line;
      res.reskey.push(item.id);
    }
  });
  return res;
}
util.mapTreeChild=function (dataArray) {
  let res={reskey:[], resvalue:''};
  for(var i=0;i<dataArray.length;i++){
    if(!dataArray[i].isRoot){
      res.resvalue+=dataArray[i].title+"/";
      res.reskey.push(dataArray[i].id);
    }
  }
  if(res.resvalue!=''){
    res.resvalue=res.resvalue.substr(0,res.resvalue.length-1);
  }
  return res;
}
util.mapTreeTxt=function (dataArray) {
  let res={reskey:[], resvalue:''};
  getTreeTxt(dataArray);
  function getTreeTxt(dataArray){
    for(var i=0;i<dataArray.length;i++){
      if(dataArray[i].isRoot){
        let treeChild=dataArray[i].children;
        getTreeTxt(treeChild);
      }else{
          if(dataArray[i].checked){
            res.resvalue+=dataArray[i].title+"/";
            res.reskey.push(dataArray[i].id);
          }
      }
    }
  }
  if(res.resvalue!=''){
    res.resvalue=res.resvalue.substr(0,res.resvalue.length-1);
  }
  return res;
}
//获取全部选中的节点包括一级节点
util.mapTreeFlat=function (dataArray) {
  let res={reskey:[], resvalue:''};
  dataArray.forEach(function (item,index){
    let line=(dataArray.length-1)==index?'':'/';
    if(item.node.checked || item.node.indeterminate){
      res.resvalue+=item.node.title+line;
      res.reskey.push(item.node.id);
    }
  });
  return res;
}
//生成选项卡标题
util.getComTitle=function (id,read,str) {
    var resStr='';
    if(id){
        if(read==1){//读取
          resStr='查看'+str;
        }else{//编辑
          resStr='修改'+str;
        }
    }else{//新增
      resStr='新增'+str;
    }
    return resStr;
}
//关闭当前Tag 跳转到父级页面
util.closeCurrentTag=function (vm,name,proute) {
  vm.$store.commit('removeTag', name);
  vm.$store.commit('closePage', name);
  vm.$store.commit('removePath',name);
  vm.$router.push({name:proute});
}
util.loginOut=function () {
  fetchGetData(adminUrl+'/admin/user/logout',{})
    .then(data=>{});
}
//跳转到指定路由
util.linkTo=function(vm,item){
  let routerObj = {};
  routerObj.name = item.name;
  if (item.argu) {
    routerObj.params = item.argu;
  }
  if (item.query) {
    routerObj.query = item.query;
  }
  vm.$router.push(routerObj);
}
util.inOf = function (arr, targetArr) {
    let res = true;
    arr.forEach(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

util.showThisRoute = function (itAccess, currentAccess) {
    if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
        return util.oneOf(currentAccess, itAccess);
    } else {
        return itAccess === currentAccess;
    }
};

util.getRouterObjByName = function (routers, name) {
    if (!name || !routers || !routers.length) {
        return null;
    }
    let routerObj = null;
    for (let item of routers) {
        if (item.name === name) {
            return item;
        }
        routerObj = util.getRouterObjByName(item.children, name);
        if (routerObj) {
            return routerObj;
        }
    }
    return null;
};
//设置当前选项卡tag以及面包屑
util.setNavTitle=function (vm,name) {
  let pageOpenedList = vm.$store.state.app.pageOpenedList;
  pageOpenedList.forEach(function (item,index) {
    if(item.name==vm.$route.name){
      item.title=name;
    }
  });
  localStorage.pageOpenedList = JSON.stringify(pageOpenedList);
  let currentPathArray=JSON.parse(localStorage.getItem("currentPath"));
  currentPathArray.forEach(function (item,index) {
    if(item.name==vm.$route.name){
      item.title=name;
    }
  });
  vm.$store.state.app.currentPath=currentPathArray;
  localStorage.setItem("currentPath",JSON.stringify(currentPathArray));
}
//设置title
util.handleTitle = function (vm, item) {
    if (typeof item.title === 'object') {
        return vm.$t(item.title.i18n);
    } else {
        return item.title;
    }
};
//设置当前路由
util.setCurrentPath = function (vm, name) {
    let title = '';
    let isOtherRouter = false;
    vm.$store.state.app.routers.forEach(item => {
        if (item.children.length === 1) {
            if (item.children[0].name === name) {
                title = util.handleTitle(vm, item);
                if (item.name === 'otherRouter') {
                    isOtherRouter = true;
                }
            }
        } else {
            item.children.forEach(child => {
                if (child.name === name) {
                    title = util.handleTitle(vm, child);
                    if (item.name === 'otherRouter') {
                        isOtherRouter = true;
                    }
                }
            });
        }
    });
    let currentPathArr = [];
    if (name === 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
                path: '',
                name: 'home_index'
            }
        ];
    } else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.routers, 'home_index')),
                path: '/home',
                name: 'home_index'
            },
            {
                title: title,
                path: '',
                name: name
            }
        ];
    } else {
        let currentPathObj = vm.$store.state.app.routers.filter(item => {
            if (item.children.length <= 1) {
                return item.children[0].name === name;
            } else {
                let i = 0;
                let childArr = item.children;
                let len = childArr.length;
                while (i < len) {
                    if (childArr[i].name === name) {
                        return true;
                    }
                    i++;
                }
                return false;
            }
        })[0];
        if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '',
                    name: 'home_index'
                }
            ];
        } else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: name
                }
            ];
        } else {
            let childObj = currentPathObj.children.filter((child) => {
                return child.name === name;
            })[0];
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: currentPathObj.name
                },
                {
                    title: childObj.title,
                    path: currentPathObj.path + '/' + childObj.path,
                    name: name
                }
            ];
        }
    }
    vm.$store.commit('setCurrentPath', currentPathArr);

    return currentPathArr;
};

util.openNewPage = function (vm, name, argu, query) {
    let pageOpenedList = vm.$store.state.app.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) { // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    if (!tagHasOpened) {
        let tag = vm.$store.state.app.tagsList.filter((item) => {
            if (item.children) {
                return name === item.children[0].name;
            } else {
                return name === item.name;
            }
        });
        tag = tag[0];
        if (tag) {
            tag = tag.children ? tag.children[0] : tag;
            if (argu) {
                tag.argu = argu;
            }
            if (query) {
                tag.query = query;
            }
            vm.$store.commit('increateTag', tag);
        }
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};

util.fullscreenEvent = function (vm) {
    vm.$store.commit('initCachepage');
};
//初始化动态路由
util.initRouter=function (vm) {
  const constRoutes = [];
  //动态路由
  // fetchGetData(adminUrl+'/admin/user/menuList',{})
  //   .then(data=>{
  //     if(data.status==1){
  //       util.initRouterNode(constRoutes, data.data);
  //       vm.$store.commit('updateAppRouter', constRoutes.filter(item => item.children.length > 0));
  //
  //       vm.$store.commit('updateMenulist', constRoutes.filter(item => item.children.length > 0));
  //
  //       let tagsList = [];
  //       vm.$store.state.app.routers.map((item) => {
  //         if (item.children.length <= 1) {
  //           tagsList.push(item.children[0]);
  //         } else {
  //           tagsList.push(...item.children);
  //         }
  //       });
  //       vm.$store.commit('setTagsList', tagsList);
  //     }
  //   });
  //静态路由
  vm.$store.commit('updateAppRouter', appRouter);
  vm.$store.commit('updateMenulist', appRouter);
  let tagsList = [];
  vm.$store.state.app.routers.map((item) => {
    if (item.children.length <= 1) {
      tagsList.push(item.children[0]);
    } else {
      tagsList.push(...item.children);
    }
  });
  vm.$store.commit('setTagsList', tagsList);

}
// 生成路由节点
util.initRouterNode = function (routers, data) {
  for (var item of data) {
    let menu = Object.assign({}, item);
    let meta={};
    if(menu.component!='Main'){
      menu.component = loadChild(menu.component);
    }else{
      menu.component = loadMain(menu.component);
    }
    if (item.children && item.children.length > 0) {
      menu.children = [];
      util.initRouterNode(menu.children, item.children);
    }
    meta.permission = menu.permission ? menu.permission : null;
    menu.meta=meta;
    routers.push(menu);
  }
};
//资源权限校验 name权限名 vm this
util.has=function (name,vm) {
  let permissions=vm.$route.meta.permission;
  if (permissions && permissions.length && !permissions.includes(name)) {
    return false;
  }else{
    return true;
  }
}
export default util;
